//添加房屋 --获取地址页面
import 'package:enjoy_plus_hm/utils/request.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class AddHouse extends StatefulWidget {
  const AddHouse({super.key});

  @override
  State<AddHouse> createState() => _AddHouseState();
}

class _AddHouseState extends State<AddHouse> {
  //经纬度
  String _latitude = '';
  String _longitude = '';
  //经过经纬度转换后的地址
  String _address = '';
  //loading框
  bool _isLoading = true;
  //周边社区
  List nearbyCommunities = [];

  @override
  void initState() {
    super.initState();
    //获取授权信息
    requestLocationPermission();
  }

  //获取权限弹窗
  Future<void> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    print({'消息是:$status'});
    if (status.isGranted) {
      //为true授权了
      ToastUtil.showInfo('授权成功!');
      getCurrentLocation();
    } else {
      ToastUtil.showError('拒绝授权则不能使用定位功能哦!');
    }
  }

  //获取经纬度的方法
  Future<void> getCurrentLocation() async {
    late LocationSettings locationSettings;

    if (defaultTargetPlatform == TargetPlatform.android) {
      // 针对Android平台，设置高精度定位、100米距离过滤、强制使用位置管理器等
      locationSettings = AndroidSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        forceLocationManager: true,
        intervalDuration: const Duration(seconds: 10),
        foregroundNotificationConfig: const ForegroundNotificationConfig(
          notificationText:
              "Example app will continue to receive your location even when you aren't using it",
          notificationTitle: "Running in Background",
          enableWakeLock: true,
        ),
      );
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      // 针对iOS和macOS平台，设置高精度定位、健身活动类型、100米距离过滤等
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // 只有在应用在后台启动时才设置为true
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      // 针对Web环境，设置高精度定位、100米距离过滤、5分钟的最大年龄等
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        maximumAge: const Duration(minutes: 5),
      );
    } else {
      // 对于其他平台，默认设置高精度定位和100米距离过滤
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }

    //使用插件Geolocator获取经纬度
    try {
      Position position = await Geolocator.getCurrentPosition(
        locationSettings: locationSettings,
      );
      // ToastUtil.showInfo('${position.latitude}, ${position.longitude}');
      setState(() {
        _isLoading = true;
        _latitude = position.latitude.toString();
        _longitude = position.longitude.toString();

        //延迟2秒
        Future.delayed(const Duration(seconds: 1), () {
          _isLoading = false;
          //获取具体位置
          getAddressInfo();
          //获取周边的社区
          getCommunity();
        });
      });
    } catch (e) {
      ToastUtil.showError('获取经纬度失败');
    }
  }

  //使用高德地图传入经纬度获取具体位置信息(逆地理编码)
  Future<void> getAddressInfo() async {
    // String url =
    //     'https://restapi.amap.com/v3/geocode/regeo?key=你的高德地图key&location=$_longitude,$_latitude';
    final res = await http.get(
      'https://restapi.amap.com/v3/geocode/regeo',
      params: {
        // 高德地图官网开发者控制台申请的密钥
        'key': 'eecec9f1b9eed3d7e519eac1c3cbd7bd',
        // 经度在前，纬度在后，经纬度间以“,”分割
        'location': '$_longitude,$_latitude',
        // 搜索半径
        'radius': 500,
        //搜索类型
        'poitype': '商务写字楼',
        // 'poitype': '商务写字楼',
        'extensions': 'all',
      },
    );
    // print(res);
    setState(() {
      _address = res['regeocode']['formatted_address'];
    });
    ToastUtil.showInfo('获取成功!');
  }

  //获取周边的社区
  Future<void> getCommunity() async {
    try {
      final res = await http.get(
        'https://restapi.amap.com/v3/place/around',
        params: {
          'key': 'eecec9f1b9eed3d7e519eac1c3cbd7bd',
          'keywords': '住房',
          'location': '$_longitude,$_latitude',
          'radius': 500,
        },
      );
      // print(res);
      setState(() {
        nearbyCommunities = res['pois'];
      });
      // print(nearbyCommunities);
    } catch (e) {
      ToastUtil.showError('获取失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 设置导航条
      appBar: AppBar(
        title: const Text('添加房屋'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      // 设置主体内容
      body: _isLoading
          ? const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 10),
                  Text('正在获取当前定位...'),
                ],
              ),
            )
          : Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              padding: const EdgeInsets.all(10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  //第一行
                  const Text(
                    '当前地址',
                    style: TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  const SizedBox(height: 10),
                  //第二行 地址+定位
                  Container(
                    padding: const EdgeInsets.all(10),
                    width: MediaQuery.of(context).size.width,
                    color: Colors.white,
                    // height: 80,
                    child: Row(
                      children: [
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              Navigator.pushNamed(
                                context,
                                '/building_list',
                                arguments: {'point': _address},
                              );
                            },
                            child: Text(_address),
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            getCurrentLocation();
                          },
                          child: const Row(
                            children: [
                              Icon(Icons.location_on, color: Colors.blue),
                              SizedBox(width: 4),
                              Text(
                                '重新定位',
                                style: TextStyle(color: Colors.blue),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 10),
                  //第三行
                  const Text(
                    '附近社区',
                    style: TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  const SizedBox(height: 10),
                  //第四行 附近社区
                  // Container(
                  //   padding: EdgeInsets.all(10),
                  //   width: MediaQuery.of(context).size.width,
                  //   color: Colors.white,
                  //   height: 50,
                  //   child: Row(
                  //     children: [
                  //       Expanded(child: Text('地址')),
                  //       //右箭头
                  //       Icon(Icons.arrow_forward_ios, size: 20),
                  //     ],
                  //   ),
                  // ),
                  Expanded(
                    child: ListView(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      children: nearbyCommunities.map((item) {
                        return Row(
                          children: [
                            Expanded(
                              child: Container(
                                padding: const EdgeInsets.all(10),
                                width: MediaQuery.of(context).size.width,
                                color: Colors.white,
                                child: GestureDetector(
                                  onTap: () {
                                    Navigator.pushNamed(
                                      context,
                                      '/building_list',
                                      arguments: {'point': item['name']},
                                    );
                                  },
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          item['name'],
                                          style: const TextStyle(
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ),
                                      //右箭头
                                      const Icon(Icons.arrow_forward_ios,
                                          size: 20),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        );
                      }).toList(),
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}
